package window

import (
	"fmt"
	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/data/binding"
	"fyne.io/fyne/v2/theme"
	"fyne.io/fyne/v2/widget"
	"log"
	"translate/config"
	"translate/tool"
	"translate/tool/translate"
)

func SetHome(w *fyne.Window) {

	win := *w
	//更改大小
	win.Resize(fyne.NewSize(300, 450))
	//设置固定大小
	//win.SetFixedSize(true)

	//创建内容
	content := makeHomeContent()

	//设置内容
	win.SetContent(content)
}

func makeHomeContent() *fyne.Container {
	//翻译内容输入框
	translateEntry := widget.NewMultiLineEntry()
	translateEntry.SetMinRowsVisible(9)
	translateEntry.Wrapping = fyne.TextWrapBreak

	//翻译结果输入框
	resultEntry := widget.NewMultiLineEntry()
	resultEntry.Wrapping = fyne.TextWrapBreak

	//选择翻译语言
	//获取所有key
	keys := make([]string, len(translate.Language))
	index := 0
	for key := range translate.Language {
		keys[index] = key
		index++
	}
	//绑定翻译语言
	targetLanguage := binding.NewString()
	err := targetLanguage.Set("简体中文")
	if err != nil {
		log.Panicln("设置初始值失败：", err.Error())
	}
	targetLanguageSelect := widget.NewSelectWithData(keys, targetLanguage)

	//翻译api
	//选择翻译内容
	translateSelect := widget.NewSelect([]string{"有道翻译", "OpenAI"}, func(s string) {
		config.Conf.Model = s
	})
	translateSelect.Selected = config.Conf.Model

	//变量提升，用于后面相应内容
	var youdao *translate.TranslateResult
	//播放按钮目标内容
	playTargetBtn := widget.NewButtonWithIcon("翻译结果", theme.VolumeUpIcon(), func() {
		log.Println("阅读翻译结果")
		go func() {
			tool.PlayAudio(youdao.Result)
		}()
	})
	playTargetBtn.Disable()
	//播放按钮原始内容
	playFromBtn := widget.NewButtonWithIcon("翻译内容", theme.VolumeUpIcon(), func() {
		log.Println("阅读翻译内容")
		go func() {
			tool.PlayAudio(youdao.Content)
		}()
	})
	playFromBtn.Disable()
	//翻译按钮
	translateBtn := widget.NewButton("   翻译   ", func() {
		log.Println("点击了翻译按钮")
		language, err := targetLanguage.Get()
		if err != nil {
			log.Panicln("获取翻译语言失败：", err.Error())
		}
		result, err := tool.Translate(language, translateEntry.Text)
		if err != nil || result.Code != "0" {
			log.Println("翻译失败：", err, result)
			resultEntry.SetText(fmt.Sprint("翻译失败：", result))
			playFromBtn.Disable()
			playTargetBtn.Disable()
			return
		}
		//设置翻译文本
		playFromBtn.Enable()
		playTargetBtn.Enable()
		resultEntry.SetText(result.Result)
		youdao = result
	})

	//返回布局
	return container.NewBorder(
		container.NewVBox(
			container.NewHBox(
				widget.NewLabel("翻译语言："),
				targetLanguageSelect,
				widget.NewLabel("翻译API："),
				translateSelect,
			),
			translateEntry,
			container.NewHBox(translateBtn, playFromBtn, playTargetBtn),
		),
		nil,
		nil,
		nil,
		resultEntry,
	)
}
